<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  
    <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="../css/style.css">
	<script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>
    
    <!-- 富文本编辑器 -->
	<link rel="stylesheet" href="../plugins/kindeditor/themes/default/default.css" />
	<script charset="utf-8" src="../plugins/kindeditor/kindeditor-min.js"></script>
	<script charset="utf-8" src="../plugins/kindeditor/lang/zh_CN.js"></script>

	<!--<%&#45;&#45;bootstrap-fileinput&#45;&#45;%>-->
	<script type="text/javascript" src="/js/bootstrap-fileinput/js/fileinput.js"></script>
	<script type="text/javascript" src="/js/bootstrap-fileinput/js/locales/zh.js"></script>
	<link rel="stylesheet" type="text/css" href="/js/bootstrap-fileinput/css/fileinput.css">
    
    
      <script>
		  $(function () {
			  getData();
			  //上传图片
			  //创建上传
			  $('#myFile').fileinput({
				  language: 'zh',
				  uploadUrl: "/goods/uploadFile",
				  allowedFileExtensions: ['jpg','png','gif','bmp'],
				  maxFileSize: 2048,
				  maxFileCount: 5,
				  enctype:"multipart/form-data",
				  initialPreviewAsData: true,//是否初始预览图片
			  });
			  //将图片名称进行回显到bimg文本框中
			  $("#myFile").on('fileuploaded',function (event,data,previewId,index) {
				  if (data.response != null){
				  	$("#uimg").val(data.response.data);
				  }
			  })
		  })
		  function getData() {
		  		var obj = 0;
			  $.ajax({
				  url:"/goods/toget1",
				  type:"post",
				  data:{id:obj},
				  dataType:"json",
				  success:function (result) {
					  var list = result.data;
					  var goods = "";
					  for (var i= 0;i<list.length;i++){
						  goods += '<option value="'+list[i].id+'">'+list[i].name+'</option>';
					  }
					  $("#goods1").html(goods);
				  },
				  error:function () {
					  alert("删除失败");
				  }
			  })
		  }
		  function toGet1(obj) {
		  	if (obj==null){
		  		alert("请选择上一级类型");
			}
			  $.ajax({
				  url:"/goods/toget1",
				  type:"post",
				  data:{id:obj},
				  dataType:"json",
				  success:function (result) {
				  	var list = result.data;
				  	var goods = "";
				  	for (var i= 0;i<list.length;i++){
						goods += '<option value="'+list[i].id+'">'+list[i].name+'</option>';
					}
				  	$("#goods2").html(goods);
				  },
				  error:function () {
					  alert("删除失败");
				  }
			  })
		  }
		  function toGet2(obj) {
			  if (obj==null){
				  alert("请选择上一级类型");
			  }
			  $.ajax({
				  url:"/goods/toget1",
				  type:"post",
				  data:{id:obj},
				  dataType:"json",
				  success:function (result) {
					  var list = result.data;
					  var goods = "";
					  for (var i= 0;i<list.length;i++){
						  goods += '<option value="'+list[i].id+'">'+list[i].name+'</option>';
					  }
					  $("#goods3").html(goods);
				  },
				  error:function () {
					  alert("删除失败");
				  }
			  })
		  }

		  var itemls = [];
		  function toGet3(obj) {
			  $.ajax({
				  url:"/goods/toGet2",
				  type:"post",
				  data:{id:obj},
				  dataType:"json",
				  success:function (result) {
					  var t = result.data.t;
					  var type = '模板ID:'+t.typeId;
					  var slist = result.data.slist;
					  $("#typeId").html(type);
					  $("#type").val(t.typeId);

					  var brand = result.data.brand.brandIds;
					  var brandIdsJson = JSON.parse(brand);
					  var brandName = "";
					  for (var j =0;j<brandIdsJson.length;j++){
						  brandName += '<option value="'+brandIdsJson[j].id+'">'+brandIdsJson[j].text+'</option>'
					  }
					  $("#brand").html(brandName);
					  //扩展属性
					  var items = result.data.brand.customAttributeItems;
					  var itemJson = JSON.parse(items);
					  $("#attribute1").text(itemJson[0].text);
					  $("#attribute2").text(itemJson[1].text);


					  //规格
						  var html = '';
						  $.each(slist,function (i,e) {
							  html +='<div><div class="col-md-2 title">'+e.text+'</div>'
							  html +='<div class="col-md-10 data">';
							  $.each(e.options,function (index,ele) {
								  html +='<span>'
								  html +='<input  onclick="checkSpec(this,\''+e.text+'\',\''+ele.optionName+'\')" ' +
										  'type="checkbox" value="'+ele.optionName+'" >'+ele.optionName+'</span>';

							  })
							  html +='</div></div>'

						  });
						  $("#dataType").html(html);

				  },
				  error:function () {
					  alert("删除失败");
				  }
			  })
		  }

		  //遍历组装用户勾选规格选项数据
		  function searchObjectByKey(list,attributeName,attributeValue){
			  for(var i=0;i<list.length;i++){
				  //如果list中我们选择key存在
				  if(list[i][attributeName] == attributeValue){
					  return list[i];//返回当前对象
				  }
			  }
			  //遍历结束后都不存在，返回null
			  return null;
		  }
		  /*			item类型
                    [     {'attributeName':'网络','attributeValue':['移动4G']}, {'attributeName':'机身内存','attributeValue':['16G','32G']}  ]
          */

		  //创建SKU列表
		  function createItemList(){
			  //创建初始值
			  var itemList = [{spec:{}}] ;
			  for(var i = 0; i < itemls.length; i++){
				  itemList  =  addColum(itemList,itemls[i].attributeName,itemls[i].attributeValue);
			  }
			  console.log(itemList);
			  var th = "";
			  th += '<tr>';
			  for(var i = 0; i < itemls.length; i++){
				  th += '<th class="sorting">'+itemls[i].attributeName+'</th>';
			  }
			  th += '<th class="sorting">价格</th>\n' +
					  '\t\t\t\t\t\t\t\t\t\t\t\t    <th class="sorting">库存</th>\n' +
					  '\t\t\t\t\t\t\t\t\t\t\t\t    <th class="sorting">是否启用</th>\n' +
					  '\t\t\t\t\t\t\t\t\t\t\t\t    <th class="sorting">是否默认</th>\n' +
					  '\t\t\t\t\t\t\t\t\t\t\t    </tr>\n';
			  $("#headForm").html(th);
			  var tr  = "";
			  for (var i = 0;i<itemList.length;i++){
				  tr += '<tr>';
				  var spec = itemList[i].spec;
				  for (var j = 0; j < itemls.length; j++){
					  tr += '<td>'+spec[itemls[j].attributeName]+'</td>';
				  }
				  tr += 	 '<td>' +
						  '<input class="form-control"  placeholder="价格">' +
						  '</td>\n' +
						  '<td>\n' +
						  '<input class="form-control" placeholder="库存数量">' +
						  '</td>\n' +
						  '<td>\n' +
						  '<input type="checkbox" name = "box">' +
						  '</td>\n' +
						  '<td>\n' +
						  '<input type="checkbox" >' +
						  '</td>\n' +
						  '</tr>';
			  }
			  $("#bodyForm").html(tr);
		  }

		  function toAdd() {
		  	//商品基本信息
			  //实例化编辑器对象
			  editor.sync();
			  //获取编辑器中输入的内容，这里我使用了id选择器去得到textarea
			  var typeTemplateId = $("#type").val();
			//商品图片
			  var options = [];
			  var table = $("#imgForm");
			  var trs = $(table).find("tr");
			  for (var i = 1;i < trs.length;i++){
				  var tds = $(trs[i]).find("td");
				  var option = {"color":$(tds[0]).html(),"url":$(tds[1]).find("input").val()};
				  options.push(option);
			  }
			  var itemImages = JSON.stringify(options);
			//扩展属性
			  var attribute1 = $("#attribute1").html();
			  var attribute2 = $("#attribute2").html();
			  var value1 = $("#value1").val();
			  var value2 = $("#value2").val();
			  var items = [];
			  var item = {"text":attribute1,"value":value1};
			  var item1 = {"text":attribute2,"value":value2};
			  items.push(item);
			  items.push(item1);
			  var customAttributeItems = JSON.stringify(items);


			  //规格\
			  //获取表格中的所有值
			  var options = [];
			  var tab  = $("#specForm");
			  var tr = $(tab).find("tr");
			  var option = {};
			  for (var i = 1;i < tr.length;i++){
				  var tds = $(tr[i]).find("td");
				  for (var j = 0; j<itemls.length;j++){
					  option[itemls[j].attributeName] = tds[j].innerHTML;
				  }
				  var OptionStrings = JSON.stringify(option);
				  var price = $(tds[itemls.length]).find("input").val();
				  var num = $(tds[itemls.length+1]).find("input").val();
				  var itemVo = {};
				  itemVo["spec"] = OptionStrings;
				  itemVo["price"] = price;
				  itemVo["num"] = num;
				  options.push(itemVo);
			  }
			  var OptionString = JSON.stringify(options);

			  //规格所有选中的规格复选框specification_items
			  /*var specItem = {};
			  for (var i = 1;i < tr.length;i++){
				  var tds = $(tr[i]).find("td");
				  for (var j = 0; j<itemls.length;j++){
					  specItem[itemls[j].attributeName] = tds[j].innerHTML;
				  }
			  }
			  var specificationItems = JSON.stringify(specItem);*/
			  //获取规格中的数据
			  var specArr = [];
			  var div = $("#dataType").children("div");
			  $.each(div, function (i, e) {
				  var attrSpec = {};
				  //拿到div的值
				  var div1 = $(e).find('div').eq(0);
				  //找到所有的input框
				  var input = $(e).find('div').eq(1).find('input');
				  attrSpec.attributeName = $(div1).html();
				  var arr = [];
				  $.each(input, function (i, ele) {
					  if ($(ele).prop("checked")) {
						  arr.push($(ele).val());
					  }
					  attrSpec.attributeValue = arr;
				  })
				  specArr.push(attrSpec)
			  })
			  var specificationItems = JSON.stringify(specArr);

			  $.ajax({
				  url:"/goods/toAdd",
				  type:"post",
				  data:$("#shopForm").serialize()+"&typeTemplateId="+typeTemplateId+"&itemImages="+itemImages+"&customAttributeItems="+customAttributeItems+"&OptionString="+OptionString+"&specificationItems="+specificationItems,
				  dataType:"json",
				  success:function (result) {
					  alert(result.message);
					  getSearch();
				  },
				  error:function () {
					  alert("删除失败");
				  }
			  })
		  }
		  function dalete(obj){
			  var d =(obj.parentNode.parentNode);
			  d.parentNode.removeChild(d);
		  }
		  function toImage() {
			  var color = $("#color").val();
			  var url = $("#uimg").val();
			  var tab=document.getElementById("imageTable");
			  var tr=document.createElement("tr");
			  tr.innerHTML='<td>' +color+'</td><td><img alt="" src="'+url+'" width="100px" height="100px" ><input type="hidden" value="'+url+'"></td><td> <button type="button" class="btn btn-default" title="删除" onclick="dalete(this)"><i class="fa fa-trash-o"></i> 删除</button></td>';
			  console.log(tr);
			  tab.appendChild(tr);
		  }

		  //勾选规格选项复选框函数
		  //复选框,规格名称,规格选项的名称
		  function checkSpec(event,name,value){
			  //调用方法判断原集合中是否已有attributeName
			  var obj = searchObjectByKey(itemls,'attributeName',name);
			  if(obj != null){
				  if($(event).prop('checked')){//勾选
					  //如果之前有数据，往原有的对象中追加
					  obj.attributeValue.push(value);
				  }else{//取消勾选
					  obj.attributeValue.splice(obj.attributeValue.indexOf(value),1)//从items中移除规格选项
					  //如果规格选项没有数据了
					  if(obj.attributeValue.length==0){
						  //移除items中的数据
						  itemls.splice(items.indexOf(obj),1)
					  }
				  }
			  }else{
				  //如果之前没有数据，items新加数据
				  itemls.push({'attributeName':name,'attributeValue':[value]});
			  }
			  //console.log(items);
			  //后续调用，这里先不调用，后续选择之后组装选择后的数据用的
			  createItemList();
		  }



		  //添加表格的列
		  function addColum(list,columName,columValues) {
			  //定义新集合接收行
			  var newList = [];
			  for(var i = 0; i < list.length; i++){
				  var oldRow = list[i];
				  for(var j=0; j < columValues.length; j++){
					  var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
					  newRow.spec[columName] = columValues[j];
					  newList.push(newRow)
				  }
			  }
			  return newList;
		  }
		  function getSearch() {
			  location.href="/seller/toHome";
		  }
	  </script>
    
    
</head>

<body class="hold-transition skin-red sidebar-mini" >

            <!-- 正文区域 -->
            <section class="content">

                <div class="box-body">

                    <!--tab页-->
                    <div class="nav-tabs-custom">

                        <!--tab头-->
                        <ul class="nav nav-tabs">                       		
                            <li class="active">
                                <a href="#home" data-toggle="tab">商品基本信息</a>                                                        
                            </li>   
                            <li >
                                <a href="#pic_upload" data-toggle="tab">商品图片</a>                                                        
                            </li>    
                            <li >
                                <a href="#customAttribute" data-toggle="tab">扩展属性</a>                                                        
                            </li>     
                            <li >
                                <a href="#spec" data-toggle="tab" >规格</a>                                                        
                            </li>                       
                        </ul>
                        <!--tab头/-->
						
                        <!--tab内容-->
                        <div class="tab-content">

                            <!--表单内容-->
                            <div class="tab-pane active" id="home">
                                <div class="row data-type">                                  
								   <div class="col-md-2 title">商品分类</div>
									<form id="shopForm">
		                           	  <div class="col-md-10 data">
		                           	  	<table>
		                           	  		<tr>
		                           	  			<td>
		                           	  				<select class="form-control" name="category1Id" id="goods1" onchange="toGet1(this.value)">
		                           	  				</select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" name="category2Id" id="goods2"  onchange="toGet2(this.value)">

													</select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" name="category3Id" id="goods3" onchange="toGet3(this.value)">

													</select>
		                              			</td>
		                              			<td id="typeId">
		                           	  				模板ID:19
		                              			</td>
		                           	  		</tr>
		                           	  	</table>
										  <input type="hidden" id="type">
		                              </div>	                              
		                          	  

		                           <div class="col-md-2 title">商品名称</div>
		                           <div class="col-md-10 data">
		                               <input type="text" name="goodsName" class="form-control"    placeholder="商品名称" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">品牌</div>
		                           <div class="col-md-10 data">
		                              <select class="form-control" name="brandId" id="brand"></select>
		                           </div>
		
								   <div class="col-md-2 title">副标题</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control" name="caption"   placeholder="副标题" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">价格</div>
		                           <div class="col-md-10 data">
		                           	   <div class="input-group">
			                          	   <span class="input-group-addon">¥</span>
			                               <input type="text" class="form-control" name="price"  placeholder="价格" value="">
		                           	   </div>
		                           </div>
		                           
		                           <div class="col-md-2 title editer">商品介绍</div>
                                   <div class="col-md-10 data editer">
                                       <textarea name="introduction"  id="content"  style="width:800px;height:400px;visibility:hidden;" ></textarea>
                                   </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">包装列表</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               
		                           	<textarea rows="4" name="packageList"  class="form-control"   placeholder="包装列表"></textarea>
		                           </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">售后服务</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               <textarea rows="4" name="saleService"  class="form-control"    placeholder="售后服务"></textarea>
		                           </div>
								</form>
                                </div>
                            </div>
                            
                            <!--图片上传-->
                            <div class="tab-pane" id="pic_upload">
                                <div class="row data-type">                                  
								 <!-- 颜色图片 -->
								 <div class="btn-group">
					                 <button type="button" class="btn btn-default" title="新建" data-target="#uploadModal"  data-toggle="modal"  ><i class="fa fa-file-o"></i> 新建</button>
                             		                 
					             </div>
								 
								 <table class="table table-bordered table-striped table-hover dataTable" id="imgForm">
					                    <thead>
					                        <tr>
					                            
											    <th class="sorting">颜色</th>
											    <th class="sorting">图片</th>
												<th class="sorting">操作</th>
											</tr>
							            </thead>
					                    <tbody id="imageTable">
					                      <!--<tr>
									            <td>
									            	
									            </td>
									            <td>
									           		<img alt="" src="" width="100px" height="100px">	            	 
									            </td>
												 <td> <button type="button" class="btn btn-default" title="删除" ><i class="fa fa-trash-o"></i> 删除</button></td> 
					                      </tr>-->
					                    </tbody>
								 </table> 
								  
                                </div>
                            </div>
                           
                           
                            <!--扩展属性-->
                            <div class="tab-pane" id="customAttribute">
                                <div class="row data-type">                                
	                                <div>
		                                <div class="col-md-2 title" id="attribute1">扩展属性1</div>
				                        <div class="col-md-10 data">
				                              <input id="value1" class="form-control" placeholder="扩展属性1">
				                        </div>
	                                </div>       
									<div>
		                                <div class="col-md-2 title" id="attribute2">扩展属性2</div>
				                        <div class="col-md-10 data">
				                              <input id="value2"  class="form-control" placeholder="扩展属性2">
				                        </div>
	                                </div>  									
                                </div>
                            </div>
                      
                            <!--规格-->
                            <div class="tab-pane" id="spec">
                            	<div class="row data-type">
	                            	<div class="col-md-2 title">是否启用规格</div>
			                        <div class="col-md-10 data">
			                        	<input type="checkbox" >			                           
			                        </div>
                            	</div>
                            	<p>
                            	
                            	<div>
                            	
	                                <div class="row data-type" id="dataType">
	                                
		                                <!--<div>
			                               <div class="col-md-2 title">屏幕尺寸</div>
					                        <div class="col-md-10 data">
					                               
					                            <span>
					                            	<input  type="checkbox" >4.0					                            				                            	
					                            </span>  	
												<span>
					                            	<input  type="checkbox" >4.5					                            				                            	
					                            </span>
												<span>
					                            	<input  type="checkbox" >5.0					                            				                            	
					                            </span>												
					                            	
					                        </div>
		                                </div>-->
		                                                                                  
	                                </div>
	
	                                
	                                <div class="row data-type">
	                                	 <table id="specForm"  class="table table-bordered table-striped table-hover dataTable">
						                    <thead id="headForm">
						                        <!--<tr>
												    <th class="sorting">屏幕尺寸</th>
													<th class="sorting">网络制式</th>
												    <th class="sorting">价格</th>
												    <th class="sorting">库存</th>
												    <th class="sorting">是否启用</th>
												    <th class="sorting">是否默认</th>
											    </tr>-->
								            </thead>
						                    <tbody  id="bodyForm">
						                      <!--<tr>
										            <td>
										            	4.0
										            </td>
													<td>
										            	3G
										            </td>
										            <td>
										           		<input class="form-control"  placeholder="价格">
										            </td>
										            <td>
										            	<input class="form-control" placeholder="库存数量">
										            </td>
										            <td>
										             	<input type="checkbox" >
										            </td>
										            <td>
										                <input type="checkbox" >									             	
										            </td>
						                      </tr>-->
						                    </tbody>
									 	</table>
								
	                                </div>
	                                
	                            </div>
                            </div>
                            
                        </div>
                        <!--tab内容/-->
						<!--表单内容/-->
							 
                    </div>
                 	
                 	
                 	
                 	
                   </div>
                  <div class="btn-toolbar list-toolbar">
				      <button type="button" class="btn btn-primary" onclick="toAdd()"><i class="fa fa-save"></i>保存</button>
				      <button class="btn btn-default" >返回列表</button>
				  </div>
			
            </section>
            
            
<!-- 上传窗口 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">上传商品图片</h3>
		</div>
		<div class="modal-body">

			<form id="addForm">
			<table class="table table-bordered table-striped">
		      	<tr>
		      		<td>颜色</td>
		      		<td><input  class="form-control" placeholder="颜色" id="color" name="color">  </td>
		      	</tr>			    
		      	<tr>
		      		<td>商品图片</td>
		      		<td>
						<table>
							<tr>
								<td>
									<input type="file" name="myFile" id="myFile" multiple>
									<input type="text" name="uimg" id="uimg">
					            </td>
							</tr>						
						</table>
		      		</td>
		      	</tr>		      	
			 </table>
			</form>
			
		</div>
		<div class="modal-footer">
			<button class="btn btn-success" type="button" onclick="toImage()"  data-dismiss="modal" aria-hidden="true">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>

            
            <!-- 正文区域 /-->
<script type="text/javascript">

	var editor;
	KindEditor.ready(function(K) {
		editor = K.create('textarea[name="introduction"]', {
			allowFileManager : true
		});
	});

</script>
       
</body>

</html>